#include "StdAfx.h"
#include "TTRegisterClient.h"
#include "TTChatConnectionListener.h"

CTTRegisterClient::CTTRegisterClient( const JID& jid,const string& password,int port/*=-1*/ )
	:Client(jid,password,-1)
{
	m_pRegister=NULL;
	m_hNoticeWnd=NULL;
	m_reg = new Registration( this );
	m_reg->registerRegistrationHandler(this);
	registerConnectionListener(this);
}

CTTRegisterClient::~CTTRegisterClient(void)
{
}

void CTTRegisterClient::onConnect()
{
	//ASSERT( m_pClient != NULL );
	//if ( m_pClient != NULL )
	//{
	//	SendMessage(m_pClient->m_hConnWnd,TTChatGlobal::TM_CONNECT_NOTIFY,NULL,NULL);
	//}
	m_reg->fetchRegistrationFields();
}

void CTTRegisterClient::onDisconnect( enum gloox::ConnectionError e )
{
	//ASSERT( m_pClient != NULL );

	//if(IsWindow(m_pClient->m_hConnWnd))
	//	SendMessage(m_pClient->m_hConnWnd,TTChatGlobal::TM_DISCONN_NOTIFY,e,NULL);
	//if(IsWindow(m_pClient->m_hMainWnd))
	//	SendMessage(m_pClient->m_hMainWnd,TTChatGlobal::TM_DISCONN_NOTIFY,e,NULL);
}

bool CTTRegisterClient::onTLSConnect( const struct gloox::CertInfo& )
{
	return true;
}

bool CTTRegisterClient::handleNormalNode( Stanza *stanza )
{
	if(m_pRegister){
		if(stanza->name()=="stream:features"&&m_pRegister->type==TTChatGlobal::RegReg){
			//fastxyf modify
			notifyOnConnect();
			return true;
		}
	}
	return false;
}

void CTTRegisterClient::handleRegistrationFields( const JID& from, int fields, std::string instructions )
{
	printf( "fields: %d\ninstructions: %s\n", fields, instructions.c_str() );
	RegistrationFields vals;
	vals.username = username();
	vals.password = password();
	vals.nick=m_pRegister->nick;
	vals.name=m_pRegister->name;
	m_reg->createAccount( fields, vals );
}

void CTTRegisterClient::handleAlreadyRegistered( const JID& from )
{

}

void CTTRegisterClient::handleRegistrationResult( const JID& from, RegistrationResult regResult )
{
	TTChatGlobal::RegNotice regNotice=TTChatGlobal::TM_REG_NOERROR;
	if(regResult==gloox::RegistrationConflict)
		regNotice=TTChatGlobal::TM_REG_EXIST;
	SendMessage(m_hNoticeWnd,TTChatGlobal::TM_MSG_REG,(WPARAM)regNotice,0);
	disconnect();
}

void CTTRegisterClient::handleDataForm( const JID& from, const DataForm &form )
{

}

void CTTRegisterClient::handleOOB( const JID& from, const OOB& oob )
{

}

void CTTRegisterClient::SetNotifyWnd( HWND hNotifyWnd )
{
	m_hNoticeWnd=hNotifyWnd;
}

void CTTRegisterClient::SetRegisterInfo( TTChatGlobal::LPTTRegistionInfo pRegInfo )
{
	m_pRegister=pRegInfo;
}
